#pragma once
#include "Socket.hpp"
#include <iostream>
#include <poll.h>
#include <sys/time.h>

static const uint16_t defaultPort = 8888;
static const int fdNumMax = 64;
static const int defaultFd = -1;
static const int non_event = 0;

class PollServer
{
public:
    PollServer(const uint16_t port = defaultPort) :_port(port)
    {
        for (int i = 0; i < fdNumMax; ++i)
        {
            _event_fds[i].fd = defaultFd;
            _event_fds[i].events = non_event;
            _event_fds[i].revents = non_event;
        }
    }

    ~PollServer()
    {}

    bool Init()
    {
        _listensock.Socket();
        _listensock.Bind(_port);
        _listensock.Listen();
        return true;
    }

    void Start()
    {
        _event_fds[0].fd = _listensock.GetFd();
        // 关注读事件
        _event_fds[0].events = POLLIN;  
        int timeout = 3000;  // 3s
        for(;;)
        {
            int n = poll(_event_fds, fdNumMax, timeout);
            switch (n)
            {
            case 0:
                std::cout << "timeout" << std::endl;
                break;
            case -1:
                std::cerr << "select error" << std::endl;
                break;
            default:
                // listen有事件就绪了,派遣任务
                // rfds是输入输出参数,此时的rfds记录的是就绪了的fd
                Dispatcher();
                break;
            }
        }
    }

    void Dispatcher()
    {
        for (int i = 0; i < fdNumMax; ++i)
        {
            int fd = _event_fds[0].fd;
            if (fd == defaultFd) continue;
            
            if (_event_fds[i].revents & POLLIN)
            {
                if (fd == _listensock.GetFd())  // 说明是listenfd就绪,代表可以Accept了
                {
                    std::cout << "Accept就绪< get a new link!" << std::endl;
                    Accepter();  // 连接管理器
                }
                else  // 说明sockfd就绪,可以进行接收报文了
                {
                    std::cout << "Recvfd就绪" << std::endl;
                    Recver(fd, i);
                }
            }
        }
    }

    void Accepter()
    {
        // 我们的连接事件就绪了,可以进行Accept了;
        std::string clientip;
        uint16_t clientport = 0;
        int sock = _listensock.Accept(&clientip, &clientport);
        if (sock < 0)
        {
            return;
        }
        LOG(Info, "accept success, %s: %d, sock fd: %d", clientip.c_str(), clientport, sock);

        // 找到_fd_array中的空位,将accept到的clientfd存放到_fd_array中,以便将accept到的客户端加入到select中
        int pos = 1;
        for (; pos < fdNumMax; ++pos)
        {
            if (_event_fds[pos].fd != defaultFd) continue;
            else break;
        }
        if (pos == fdNumMax)
        {
            LOG(Warning, "server is full, close %d now!", sock);
            close(sock);
        }
        else
        {
            // 将accept到的clientfd存放到_fd_array中,以便将accept到的客户端加入到select中
            _event_fds[pos].fd = sock;
            _event_fds[pos].events = POLLIN;
            _event_fds[pos].revents = non_event;
            PrintFd();
        }
    }

    void Recver(int fd, int pos)
    {
        char buffer[1024];
        ssize_t n = read(fd, buffer, sizeof(buffer) - 1);  // 实际中Tcp按字节流发包,应用层需要需要定制协议来判断是否接收完整
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "get a message: " << buffer << std::endl;
        }
        else if (n == 0)
        {
            LOG(Info, "client quit, me too, close fd: %d", fd);
            close(fd);
            _event_fds[pos].fd == defaultFd;  // 本质就算将该客户端的fd从select中移除
        }
        else
        {
            LOG(Warning, "recv error, fd: %d", fd);
            close(fd);
            _event_fds[pos].fd = defaultFd;  // 本质就算将该客户端的fd从select中移除
        }
    }

    void PrintFd()
    {
        std::cout << "online fd list: ";
        for (int i = 0; i < fdNumMax; i++)
        {
            if (_event_fds[i].fd == defaultFd)
                continue;
            std::cout << _event_fds[i].fd << " ";
        }
        std::cout << std::endl;
    }

private:
    Sock _listensock;
    uint16_t _port;
    struct pollfd _event_fds[fdNumMax];
};